package com.it.plic.constructors;

import com.it.plic.constructors.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author げっしょく
 * @date 2021/8/9
 */
public class Test1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //method1();
        //method2();
        //获得类的对象
        Class ac = Class.forName("com.it.plic.constructors.Student");
        ////获得构造构造对象
        Constructor cs = ac.getConstructor(String.class, int.class);
        //通过有参构造创建对象
        Student ls = (Student) cs.newInstance("lisi", 20);
        System.out.println(ls);
    }

    private static void method2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获得类的对象
        Class ac = Class.forName("com.it.plic.constructors.Student");
        //获得私有构造对象
        Constructor name = ac.getDeclaredConstructor(String.class);
        //私有构造不能直接创建对象
        //需要临时取消访问检查
        name.setAccessible(true);
        //创建对象
        Student s = (Student) name.newInstance("zhangsan");
        System.out.println(s);
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获得类的对象
        Class ac = Class.forName("com.it.plic.constructors.Student");
        //获得构造构造对象
        Constructor cs = ac.getConstructor();
        //通过无参构造创建对象
        Student s = (Student) cs.newInstance();
        System.out.println(s);
    }
}
